package com.diu.domain.strategy.service.rule.chain.impl;

import com.diu.domain.strategy.model.entity.StrategyRuleEntity;
import com.diu.domain.strategy.repository.IStrategyRepository;
import com.diu.domain.strategy.service.armory.IStrategyDispatch;
import com.diu.domain.strategy.service.armory.StrategyArmoryDispatch;
import com.diu.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.diu.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author #diu
 * @description #
 * @create #2025/10/14 11:20
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch strategyDispatch;

    private final Long userScore = 300L; // 用户积分，后续需要从数据库中查询

    @Override
    public Integer logic(String userId, Long strategyId){
        log.info("权重过滤器触发，userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, null, ruleModel());
        // 1.根据用户ID查询用户抽奖消耗的积分值，本章节先写死为固定的值，后续需要从数据库中查询
        Map<Long,String> analyticalValueGroup = getAnalyticalValue(ruleValue);

        // 2.转换Keys值，并默认排序
        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys);

        Long ruleId = analyticalSortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);
        if(ruleId != null) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, ruleId+"");// 这里我的key是不带规则包含的具体奖品的
            log.info("抽奖责任链-权重接管 userId:{} strategyId:{} ruleModel:{} awardId:{}", userId, strategyId,ruleModel(),awardId);
            return awardId;
        }

        // 3.过滤其他规则链
        log.info("抽奖责任链-权重放行 userId:{} strategyId:{} ruleModel:{}", userId, strategyId,ruleModel());
        return next().logic(userId, strategyId);
    }

    public Map<Long,String> getAnalyticalValue(String ruleValue){
        // 解析规则值
        // 规则值格式：1001:101,102,103 1002:30,31,32 1003:20
        // 奖品ID:权重,奖品ID:权重
        Map<Long,String> analyticalValueGroup = new HashMap<>();
        if(ruleValue != null && !ruleValue.isEmpty()){
            String[] splitRuleValues = ruleValue.split(Constants.SPACE);
            for(String rule : splitRuleValues){
                Long ruleValueId = Long.valueOf(rule.split(Constants.COLON)[0]);
                String ruleParts = rule.split(Constants.COLON)[1];
                analyticalValueGroup.put(ruleValueId, ruleParts);
            }
        }
        return analyticalValueGroup;
    }

    @Override
    public String ruleModel() {
        return "rule_weight";
    }
}
